package com.itheima.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UploadController {

    /**
     *  注意参数名跟前端name属性一致
     * @param username
     * @param password
     * @param myFile  本质是个InputStream
     *            springmvc用这个对象封装了前端发送的文件数据
     *               限制大小: 10M
     *
     * @return
     */
    @PostMapping("/uploadfile")
    public String demo(String username, String password,
                       MultipartFile myFile) throws IOException {
        System.out.println(username + "," + password);
        String name = myFile.getName();
        System.out.println("属性名:" + name);
        String originalFilename = myFile.getOriginalFilename();
        System.out.println("文件名:" + originalFilename);
        //随机文件名
        String randomName = UUID.randomUUID().toString().replaceAll("-", "");
        //6.jpg为例, 6 jpg
        String[] split = originalFilename.split("\\.");
        String fileName  = "c:/test/upload/" + randomName + "." + split[1];

        File destFile = new File(fileName);
        //将myFile数据写到destFile去
        myFile.transferTo(destFile);
        return "success";
    }

}